import random


class EliminationGameController:
    """
        游戏控制器
    """

    def __init__(self):
        self.__list_map = [
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0]
        ]

    @property
    def list_map(self):
        return self.__list_map

    def start_list_map(self):
        for r in range(len(self.__list_map)):
            for c in range(len(self.__list_map[r])):
                self.__list_map[r][c] = random.randint(1, 5)

    def append_random_generation_number(self):
        """
            在二维列表中随机一个位置生成1-9中某个数
        """
        while True:
            r = random.randint(0, 7)
            c = random.randint(0, 7)
            if self.__list_map[r][c] == 0:
                self.__list_map[r][c] = random.randint(1, 5)
                break

    @staticmethod
    def __move_zero_to_end(list_target):
        """
            将每行中的0元素移动到末尾
        :param list_target: list类型,每一行元素列表
        """
        for i in range(len(list_target) - 1, -1, -1):
            if list_target[i] == 0:
                del list_target[i]
                list_target.append(0)

    def __merge(self, list_target):
        """
            将每行元素左移合并
        :param list_target: list类型,每一行元素列表
        """
        self.__move_zero_to_end(list_target)
        for i in range(len(list_target) - 1):
            if list_target[i] == list_target[i + 1]:
                list_target[i] += list_target[i + 1]
                del list_target[i + 1]
                list_target.append(0)

    def move_to_left(self):
        """
            左移二维列表
        """
        for line in self.__list_map:
            self.__merge(line)

    def move_to_right(self):
        """
            右移二维列表
        """
        for line in self.__list_map:
            list_line = line[::-1]
            self.__merge(list_line)
            line[::-1] = list_line

    def __transposed_map(self):
        """
            矩阵转置
        """
        new_map = [list(line) for line in zip(*self.__list_map)]
        self.__list_map[:] = new_map

    def move_to_up(self):
        """
            上移二维列表
        """
        self.__transposed_map()
        self.move_to_left()
        self.__transposed_map()

    def move_to_down(self):
        """
            下移二维列表
        """
        self.__transposed_map()
        self.move_to_right()
        self.__transposed_map()
